"""
主窗口类
负责整体布局和组件协调
"""

import sys
import traceback
from pathlib import Path

from PySide6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
    QSplitter, QTabWidget, QMessageBox, QStatusBar
)
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QIcon

from src.core.detector import PlateDetector
from src.core.recognizer import PlateRecognizer
from src.core.processor import ImageProcessor
from src.utils.config import Config
from src.utils.logger import Logger

from .widgets import (
    VideoDisplayWidget, ImageDisplayWidget, 
    ResultDisplayWidget, MenuBarWidget
)


class MainWindow(QMainWindow):
    """
    主窗口类
    
    功能：
    - 整体布局管理
    - 组件协调
    - 模型初始化
    - 事件处理
    """
    
    def __init__(self):
        super().__init__()
        
        # 初始化组件
        self.config = Config()
        self.logger = Logger()
        
        # 模型组件
        self.detector = None
        self.recognizer = None
        self.processor = None
        
        # UI组件
        self.menu_bar_widget = None
        self.image_display = None
        self.video_display = None
        self.result_display = None
        
        # 初始化
        self.init_ui()
        self.init_models()
        self.connect_signals()
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("实时车牌识别系统")
        self.setGeometry(100, 100, 1200, 800)
        
        # 创建菜单栏
        self.menu_bar_widget = MenuBarWidget(self)
        menu_bar = self.menu_bar_widget.create_menu_bar()
        self.setMenuBar(menu_bar)
        
        # 创建工具栏
        toolbar = self.menu_bar_widget.create_tool_bar()
        self.addToolBar(toolbar)
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("准备就绪")
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        
        # 左侧：显示区域
        self._create_display_area(splitter)
        
        # 右侧：结果区域
        self._create_result_area(splitter)
        
        # 设置分割器比例
        splitter.setSizes([800, 400])
        main_layout.addWidget(splitter)
        
    def _create_display_area(self, parent):
        """创建显示区域"""
        # 创建选项卡
        tab_widget = QTabWidget()
        
        # 图片显示选项卡
        self.image_display = ImageDisplayWidget()
        tab_widget.addTab(self.image_display, "图片检测")
        
        # 视频显示选项卡
        self.video_display = VideoDisplayWidget()
        tab_widget.addTab(self.video_display, "视频检测")
        
        parent.addWidget(tab_widget)
        
    def _create_result_area(self, parent):
        """创建结果区域"""
        self.result_display = ResultDisplayWidget()
        parent.addWidget(self.result_display)
        
    def init_models(self):
        """初始化模型"""
        try:
            self.status_bar.showMessage("正在加载模型...")
            
            # 初始化处理器
            self.processor = ImageProcessor()
            
            # 初始化检测器
            detector_config = self.config.get('model.detector', {})
            self.detector = PlateDetector(config=detector_config)
            
            # 初始化识别器
            recognizer_config = self.config.get('model.recognizer', {})
            self.recognizer = PlateRecognizer(config=recognizer_config)
            
            # 设置模型到显示组件
            self.image_display.set_models(self.detector, self.recognizer, self.processor)
            self.video_display.set_models(self.detector, self.recognizer, self.processor)
            
            self.status_bar.showMessage("模型加载完成")
            self.logger.info("所有模型初始化完成")
            
        except Exception as e:
            error_msg = f"模型初始化失败: {e}"
            self.logger.error(error_msg)
            self.status_bar.showMessage(error_msg)
            QMessageBox.critical(self, "错误", error_msg)
            
    def connect_signals(self):
        """连接信号"""
        # 菜单栏信号
        self.menu_bar_widget.openImageRequested.connect(self.open_image)
        self.menu_bar_widget.openVideoRequested.connect(self.open_video)
        self.menu_bar_widget.openCameraRequested.connect(self.open_camera)
        self.menu_bar_widget.aboutRequested.connect(self.menu_bar_widget.show_about)
        self.menu_bar_widget.exitRequested.connect(self.close)
        
        # 检测结果信号
        self.image_display.resultReady.connect(self.result_display.add_result)
        self.video_display.resultReady.connect(self.result_display.add_result)
        
    def open_image(self, file_path):
        """打开图片文件"""
        try:
            self.status_bar.showMessage(f"正在处理图片: {Path(file_path).name}")
            self.image_display.process_image(file_path)
            self.status_bar.showMessage("图片处理完成")
            
        except Exception as e:
            error_msg = f"图片处理失败: {e}"
            self.logger.error(f"{error_msg}\n{traceback.format_exc()}")
            self.status_bar.showMessage(error_msg)
            QMessageBox.critical(self, "错误", error_msg)
            
    def open_video(self, file_path):
        """打开视频文件"""
        try:
            self.status_bar.showMessage(f"正在加载视频: {Path(file_path).name}")
            self.video_display.set_source(file_path)
            self.status_bar.showMessage("视频加载完成，点击播放开始检测")
            
        except Exception as e:
            error_msg = f"视频加载失败: {e}"
            self.logger.error(f"{error_msg}\n{traceback.format_exc()}")
            self.status_bar.showMessage(error_msg)
            QMessageBox.critical(self, "错误", error_msg)
            
    def open_camera(self, camera_id):
        """打开摄像头"""
        try:
            self.status_bar.showMessage(f"正在打开摄像头 {camera_id}")
            self.video_display.set_source(camera_id)
            self.status_bar.showMessage("摄像头已就绪，点击播放开始检测")
            
        except Exception as e:
            error_msg = f"摄像头打开失败: {e}"
            self.logger.error(f"{error_msg}\n{traceback.format_exc()}")
            self.status_bar.showMessage(error_msg)
            QMessageBox.critical(self, "错误", error_msg)
            
    def closeEvent(self, event):
        """关闭事件处理"""
        try:
            # 停止视频线程
            if self.video_display:
                self.video_display.stop_video()
                
            self.logger.info("程序正常退出")
            event.accept()
            
        except Exception as e:
            self.logger.error(f"程序退出时发生错误: {e}")
            event.accept() 